<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onBeforeMount, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { Zoom } from 'swiper/modules'
import { Swiper, SwiperSlide } from 'swiper/vue'
import 'swiper/css'
import 'swiper/css/zoom'
import html2canvas from 'html2canvas'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* ---- */
const user = reactive({
  info: '销售合同',
  // ----
  imageShow: false,
  imageData: '',
  // ----
  btnImgTxt: '',
  btnSignTxt: '',
  // ----
  title: '',
  // ----
  share_title: proxy.$shareTitle,
  share_desc: proxy.$shareDesc,
  share_icon: proxy.$shareIcon,
  // ----
  isSignRequired: false,
  isImgCreate: false
})
// ----
const modules = [Zoom]
// ----
let types = []
let sizes = []
let units = []
// ----
const goods = ref([])
const terms = ref([])
// ----
const contract = reactive({
  date: '',
  coding: '',
  isSign: true,
  signImg: '',
  // ----
  stampImg: '',
  // ----
  giveName: '',
  giveLeader: '',
  giveTelphone: '',
  sentLeader: '',
  sentTelphone: '',
  sentAddress: '',
  // ----
  pickName: '',
  pickLeader: '',
  pickTelphone: '',
  takeLeader: '',
  takeTelphone: '',
  takeAddress: '',
  // ----
  totalAmount: '0.00'
})

/* ---- */
const esign = ref()
const stamp = ref()
const layer = ref()

/* ---- */
const setAppTitle = (title) => {
  document.title = title
  // --利用iframe的onload事件刷新页面--
  const iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = 0
  iframe.style.height = 0
  document.body.appendChild(iframe)
  nextTick(() => { document.body.removeChild(iframe) })
}
// --设置微信分享--
const setWebShare = (info) => {
  const forSn = proxy.$Store.get('SN')
  const currentUrl = window.location.href.split('#')[0]
  const shareLink = (Number(currentUrl.indexOf('sn=')) === Number(-1)) ? ((Number(currentUrl.indexOf('?')) === Number(-1)) ? currentUrl + '?sn=' + forSn : currentUrl + '&sn=' + forSn) : currentUrl
  proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
    if (!obj) return
    // ----
    obj.hideMenuItem()
    obj.showMenuList(['menuItem:share:appMessage', 'menuItem:share:timeline', 'menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:favorite', 'menuItem:share:QZone'])
    // ----
    obj.share({
      title: info.title,
      desc: info.desc,
      link: shareLink,
      imgUrl: info.imgUrl
    })
  })
}
// ----
const getFootShow = () => {
  if (proxy.$route.query.sn) {
    user.isSignRequired = !contract.isSign && Number(contract.signImg.length) === 0
  } else {
    user.isImgCreate = contract.isSign && Number(contract.signImg.length) > 0
  }
}
// ----
const getCurrencyInfo = async (callback) => {
  // -- 获取商品型号 && 商品规格 && 商品计量单位 && 订购合同信息 && 订购合同分享设置 --
  const forTypeData = {
    params: {
      'CommonTypeSearch[dealer_id]': proxy.$route.query.dealer_id,
      // --电子合同商品型号--
      'CommonTypeSearch[type]': 2,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  const forSizeData = {
    params: {
      'CommonTypeSearch[dealer_id]': proxy.$route.query.dealer_id,
      // --电子合同商品规格--
      'CommonTypeSearch[type]': 3,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  const forUnitData = {
    params: {
      'CommonTypeSearch[dealer_id]': proxy.$route.query.dealer_id,
      // --电子合同计量单位--
      'CommonTypeSearch[type]': 4,
      // ----
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  const forContractData = { params: { 'ContractSearch[id]': proxy.$route.query.id } }
  const forShareData = {
    params: {
      'SharewxSearch[dealer_id]': proxy.$route.query.dealer_id,
      // --电子合同分享设置--
      'SharewxSearch[type]': 1
    }
  }
  await proxy.$Axios.all([
    proxy.$Axios.get('common-type/index', forTypeData),
    proxy.$Axios.get('common-type/index', forSizeData),
    proxy.$Axios.get('common-type/index', forUnitData),
    proxy.$Axios.get('contract/index', forContractData),
    proxy.$Axios.get('sharewx/index', forShareData)
  ]).then(proxy.$Axios.spread((typeData, sizeData, unitData, contractData, shareData) => {
    // --商品型号--
    const typeItems = []
    typeData.items.forEach((item, index) => {
      typeItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    types = typeItems
    // --商品规格--
    const sizeItems = []
    sizeData.items.forEach((item, index) => {
      sizeItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    sizes = sizeItems
    // --商品计量单位--
    const unitItems = []
    unitData.items.forEach((item, index) => {
      unitItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    units = unitItems
    // --订购合同信息--
    if (contractData.items && Number(contractData.items.length) > 0) {
      const CTData = contractData.items[0]
      // ----
      contract.date = proxy.$Myfun.getDateShort(CTData.make_date)
      contract.coding = CTData.sn
      contract.isSign = Number(CTData.is_sign) === 1
      proxy.$Myfun.getJsonData(CTData.cg_sign, (resJson) => {
        if (Number(resJson.length) > 0) contract.signImg = resJson[0].image
      })
      // ----
      contract.giveName = proxy.$Myfun.setText(CTData.gh_name)
      contract.giveLeader = proxy.$Myfun.setText(CTData.gh_leader)
      contract.giveTelphone = CTData.gh_telphone
      contract.sentLeader = proxy.$Myfun.setText(CTData.gh_wlleader)
      contract.sentTelphone = CTData.gh_wltelphone
      contract.sentAddress = proxy.$Myfun.setText(CTData.gh_address)
      // ----
      contract.pickName = proxy.$Myfun.setText(CTData.name)
      contract.pickLeader = proxy.$Myfun.setText(CTData.cg_leader)
      contract.pickTelphone = CTData.cg_telphone
      contract.takeLeader = proxy.$Myfun.setText(CTData.sh_leader)
      contract.takeTelphone = CTData.sh_telphone
      contract.takeAddress = proxy.$Myfun.setText(CTData.sh_address)
      // ----
      contract.totalAmount = proxy.$Myfun.setText(CTData.total_amount)
      // ----
      const goodsItems = []
      proxy.$Myfun.getJsonData(CTData.pro_arr, (resJson) => {
        resJson.forEach((item) => {
          let forTypeTxt = proxy.$Myfun.setText(item.typeTxt)
          let forSizeTxt = proxy.$Myfun.setText(item.sizeTxt)
          let forunitTxt = proxy.$Myfun.setText(item.unitTxt)
          if (!contract.isSign && Number(contract.signImg.length) === 0) {
            types.some((current) => {
              if (String(current.value) === String(item.type)) forTypeTxt = current.text
            })
            sizes.some((current) => {
              if (String(current.value) === String(item.size)) forSizeTxt = current.text
            })
            units.some((current) => {
              if (String(current.value) === String(item.unit)) forunitTxt = current.text
            })
          }
          // ----
          goodsItems.push({
            type: item.type,
            typeTxt: forTypeTxt,
            size: item.size,
            sizeTxt: forSizeTxt,
            count: item.count,
            unit: item.unit,
            unitTxt: forunitTxt,
            price: Number(item.price).toFixed(2),
            amount: Number(item.amount).toFixed(2)
          })
        })
      })
      if (Number(goodsItems.length) > 0) goods.value = goodsItems
      // ----
      const termsItems = []
      proxy.$Myfun.getJsonData(CTData.terms, (resJson) => {
        resJson.forEach((item) => {
          termsItems.push({
            text: item.text
          })
        })
      })
      if (Number(termsItems.length) > 0) terms.value = termsItems
    }
    // --订购合同分享设置--
    const SEData = shareData.items[0] || {}
    if (SEData.name && Number(SEData.name.length) > 0) user.share_title = proxy.$Myfun.setText(SEData.name)
    if (Number(contract.pickName.length) > 0) user.share_desc = '采购单位：' + contract.pickName
    proxy.$Myfun.getJsonData(SEData.img_json, (resJson) => {
      if (Number(resJson.length) > 0) user.share_icon = resJson[0].image
    })
    // ----
    proxy.$Myfun.getJsonData(SEData.content, (resJson) => {
      if (resJson[0].imgTxt) user.btnImgTxt = resJson[0].imgTxt
      if (resJson[0].signTxt) user.btnSignTxt = resJson[0].signTxt
    })
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  if (Number(contract.giveName.length) > 0) getAuditFun(1)
  // --设置网页title--
  const forTitle = user.title ? String(user.title + document.title) : document.title
  setAppTitle(forTitle)
  // --设置微信分享信息--
  const forShare = {
    title: user.share_title,
    desc: user.share_desc,
    imgUrl: user.share_icon
  }
  setWebShare(forShare)
  // ----
  callback && callback()
}
// ----
const getAuditFun = (type) => {
  switch (Number(type)) {
    case 1: {
      const options = {
        name: contract.giveName,
        info: '合同专用章',
        // ----
        callback: (result) => { if (result) contract.stampImg = result }
      }
      proxy.$Myfun.isIndepth(stamp.value, 'open', options)
      break
    }
    case 2: {
      user.imageShow = false
      break
    }
    case 3: {
      const element = proxy.$refs.pdfContent
      // ----
      html2canvas(element, {
        allowTaint: true,
        useCORS: true,
        scale: 1,
        width: element.offsetWidth,
        height: element.offsetHeight
      }).then(async (canvas) => {
        user.imageData = canvas.toDataURL('image/png', 1.0)
        // ----
        setTimeout(() => { user.imageShow = true }, 100)
      })
      break
    }
    case 4: {
      const options = {
        title: '请在屏幕上手写名字',
        cancel: {
          text: proxy.$Global.layer.btnCancel,
          class: 'xw-btn xw-WBlack'
        },
        reset: {
          text: '清空重签',
          class: 'xw-btn xw-WBlack'
        },
        button: {
          text: '确定提交',
          class: 'xw-btn xw-bgCL-11 xw-act',
          callback: async (signData) => {
            let resData = ''
            await proxy.$http.get('contract/index', {
              params: { 'ContractSearch[id]': proxy.$route.query.id }
            }).then((res) => { resData = res.items[0] }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
            // ----
            if (resData && Number(resData.is_sign) === 1 && Number(resData.cg_sign.length) > 0) {
              contract.isSign = true
              proxy.$Myfun.getJsonData(resData.cg_sign, (resJson) => { contract.signImg = resJson[0].image })
              // ----
              getFootShow()
              // ----
              return false
            }
            // --上传签名文字图片--
            const options = {
              region: proxy.$Global.aoss.region,
              bucket: proxy.$Global.aoss.bucket,
              accessKeyId: proxy.$Global.aoss.accessKeyId,
              accessKeySecret: proxy.$Global.aoss.accessKeySecret,
              // ----
              folder: proxy.$Global.aoss.folder + proxy.$Myfun.getDateFolder(),
              fileName: proxy.$Myfun.getDateName() + '.' + signData.suffix
            }
            proxy.$OssUp.ossUpload(options, signData.url).then((upRes) => {
              if (upRes && upRes.url) {
                const signs = [{
                  name: upRes.name,
                  image: upRes.url,
                  width: signData.W,
                  height: signData.H
                }]
                const forSings = JSON.stringify(signs)
                proxy.$http.patch('contract/update?id=' + proxy.$route.query.id, {
                  is_sign: 1,
                  cg_sign: forSings,
                  // ----
                  config_id: userInfo.config_id,
                  openid: userInfo.openid
                }).then((res) => {
                  if (res) {
                    contract.isSign = true
                    contract.signImg = upRes.url
                    // ----
                    getFootShow()
                  }
                }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
              }
            })
          },
          fail: () => { proxy.$Myfun.forToast(layer.value, 'open', '请签字后再提交！') }
        }
      }
      proxy.$Myfun.isIndepth(esign.value, 'open', options)
      break
    }
  }
}

/* ---- */
onBeforeMount(() => {
  getCurrencyInfo(() => {
    getFootShow()
  })
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="xw-bg-white" :class="{'CTT-view': user.isSignRequired || user.isImgCreate}">
      <div class="CTT-box" ref="pdfContent">
        <div class="CTT-name">销售合同</div>
        <div class="CTT-top xw-flex xw-flex-align xw-flex-justify">
          <div>制定时间：{{contract.date}}</div>
          <div>合同编号：{{contract.coding}}</div>
        </div>
        <div class="CTT-give xw-Tfg">
          <div class="CTT-give-item xw-flex">
            <div class="CTT-give-name">供货单位：</div>
            <div class="xw-flex-W1">{{contract.giveName}}</div>
          </div>
          <div class="CTT-give-item xw-flex xw-flex-align">
            <div class="xw-ellipsis xw-flex-W1"><span class="xw-color-13">业务负责：</span>{{contract.giveLeader}}</div>
            <div class="xw-flex-W1"><span class="xw-color-13">联系方式：</span>{{contract.giveTelphone}}</div>
          </div>
          <div class="CTT-give-item xw-flex xw-flex-align">
            <div class="xw-ellipsis xw-flex-W1"><span class="xw-color-13">物流负责：</span>{{contract.sentLeader}}</div>
            <div class="xw-flex-W1"><span class="xw-color-13">联系方式：</span>{{contract.sentTelphone}}</div>
          </div>
          <div class="CTT-give-item xw-flex">
            <div class="xw-color-13">发货地址：</div>
            <div class="CTT-give-addr xw-flex-W1">{{contract.sentAddress}}</div>
          </div>
        </div>
        <div class="CTT-pick xw-Tfg">
          <div class="CTT-pick-item xw-flex">
            <div class="CTT-pick-name">采购单位：</div>
            <div class="xw-flex-W1">{{contract.pickName}}</div>
          </div>
          <div class="CTT-pick-item xw-flex xw-flex-align">
            <div class="xw-ellipsis xw-flex-W1"><span class="xw-color-13">采购负责：</span>{{contract.pickLeader}}</div>
            <div class="xw-flex-W1"><span class="xw-color-13">联系方式：</span>{{contract.pickTelphone}}</div>
          </div>
          <div class="CTT-pick-item xw-flex xw-flex-align">
            <div class="xw-ellipsis xw-flex-W1"><span class="xw-color-13">收货负责：</span>{{contract.takeLeader}}</div>
            <div class="xw-flex-W1"><span class="xw-color-13">联系方式：</span>{{contract.takeTelphone}}</div>
          </div>
          <div class="CTT-pick-item xw-flex">
            <div class="xw-color-13">收货地址：</div>
            <div class="CTT-pick-addr xw-flex-W1">{{contract.takeAddress}}</div>
          </div>
        </div>
        <div class="CTT-goods xw-Tfg" v-if="Number(goods.length) > 0">
          <ul class="CTT-goods-list xw-flex xw-flex-column">
            <li v-for="(item, index) in goods">
              <div class="CTT-goods-name">采购商品{{index + 1}}</div>
              <div class="CTT-goods-info">
                <table>
                  <tr>
                    <td colspan="2"><div class="CTT-goods-item xw-flex">
                      <em class="xw-color-13">型号：</em>
                      <span>{{item.typeTxt}}</span>
                    </div></td>
                  </tr>
                  <tr class="CTT-goods-tr">
                    <td><div class="CTT-goods-item xw-flex xw-flex-align">
                      <em class="xw-color-13">规格：</em>
                      <span>{{item.sizeTxt}}</span>
                    </div></td>
                    <td><div class="CTT-goods-item xw-flex xw-flex-align">
                      <em class="xw-color-13">数量：</em>
                      <span>{{item.count}}</span>
                      <span v-if="item.unitTxt">{{item.unitTxt}}</span>
                    </div></td>
                  </tr>
                  <tr class="CTT-goods-tr">
                    <td><div class="CTT-goods-item xw-flex xw-flex-align">
                      <em class="xw-color-13">单价：</em>
                      <span>{{item.price}}</span>
                      <span>元</span>
                      <span v-if="item.unitTxt">/{{item.unitTxt}}</span>
                    </div></td>
                    <td><div class="CTT-goods-item xw-flex xw-flex-align">
                      <em class="xw-color-13">金额：</em>
                      <span>{{item.amount}}</span>
                      <span>元</span>
                    </div></td>
                  </tr>
                </table>
              </div>
            </li>
          </ul>
          <div class="CTT-goods-total xw-flex xw-flex-align">
            <span>合计总金额：</span>
            <span>{{contract.totalAmount}}</span>
            <span>元</span>
          </div>
        </div>
        <div class="CTT-terms xw-Tfg" v-if="Number(terms.length) > 0">
          <div class="CTT-terms-name">约定条款</div>
          <ul class="CTT-terms-list xw-flex xw-flex-column">
            <li v-for="(item, index) in terms">{{Number(index + 1)}}、{{item.text}}</li>
          </ul>
        </div>
        <div class="CTT-sealsign xw-flex">
          <div class="CTT-seal xw-flex-W1 xw-flex xw-flex-column">
            <b>供货单位盖章：</b>
            <div class="CTT-seal-img"><img :src="contract.stampImg"/></div>
          </div>
          <div class="CTT-sign xw-flex-W1 xw-flex xw-flex-column">
            <b>采购方负责人：</b>
            <div class="CTT-sign-img" v-if="contract.isSign || Number(contract.signImg.length) > 0"><img :src="contract.signImg"/></div>
          </div>
        </div>
      </div>
    </div>
    <transition name="fade"><div class="xw-full" v-if="user.imageShow && (contract.isSign || Number(contract.signImg.length) > 0)">
      <swiper :modules="modules" :zoom="true" class="album-box">
        <swiper-slide>
          <div class="swiper-zoom-container"><img :src="user.imageData"/></div>
        </swiper-slide>
      </swiper>
      <div class="FBR-box xw-flex xw-flex-align xw-flex-justify">
        <div class="FBR-title">长按图片保存到手机即可</div>
        <div class="FBR-close xw-act" @click="getAuditFun(2)">返回</div>
      </div>
    </div></transition>
    <footer v-if="user.isImgCreate">
      <div class="tabs xw-foot-Tfg xw-flex xw-flex-align">
        <div class="TAB-mbtn xw-radius-3 xw-bgCL-11 xw-act xw-ellipsis xw-flex-W1" @click="getAuditFun(3)">{{user.btnImgTxt}}</div>
      </div>
    </footer>
    <footer v-if="user.isSignRequired">
      <div class="tabs xw-foot-Tfg xw-flex xw-flex-align">
        <div class="TAB-mbtn xw-radius-3 xw-bgCL-11 xw-act xw-ellipsis xw-flex-W1" @click="getAuditFun(4)">{{user.btnSignTxt}}</div>
      </div>
    </footer>
    <esign-view ref="esign"/>
    <stamp-view ref="stamp"/>
    <layer-view ref="layer"/>
  </div>
</template>

<style scoped>
/* ---- */
.CTT-view { margin: 0 0 6.4rem; }
.CTT-box { margin-top: -4rem; padding: 1.6rem 1rem; }
.CTT-name { padding: 0 0 1.6rem; line-height: 2.5rem; font-size: 1.9rem; font-weight: bold; text-align: center; }
.CTT-pick { margin: 1.2rem 0 0; padding: 1.2rem 0 0; }
.CTT-pick-item { margin: 0.5rem -0.5rem 0; line-height: 2rem; }
.CTT-pick-item div { margin: 0 0.5rem; }
.CTT-pick .CTT-pick-item:nth-of-type(1), .CTT-pick .CTT-pick-item:last-child { margin: 0.5rem 0 0; }
.CTT-pick .CTT-pick-item:nth-of-type(1) { line-height: 2.5rem; }
.CTT-pick .CTT-pick-item:nth-of-type(1) div, .CTT-pick .CTT-pick-item:last-child div { margin: 0; }
.CTT-pick-name { font-size: 1.7rem; font-weight: bold; text-align: justify; }
.CTT-pick-addr { text-align: justify; }
.CTT-give { margin: 1.2rem 0 0; padding: 1.2rem 0 0; }
.CTT-give-item { margin: 0.5rem -0.5rem 0; line-height: 2rem; }
.CTT-give-item div { margin: 0 0.5rem; }
.CTT-give .CTT-give-item:nth-of-type(1), .CTT-give .CTT-give-item:last-child { margin: 0.5rem 0 0; }
.CTT-give .CTT-give-item:nth-of-type(1) { line-height: 2.5rem; }
.CTT-give .CTT-give-item:nth-of-type(1) div, .CTT-give .CTT-give-item:last-child div { margin: 0; }
.CTT-give-name { font-size: 1.7rem; font-weight: bold; text-align: justify; }
.CTT-give-addr { text-align: justify; }
.CTT-goods { margin: 1.2rem 0 0; padding: 1.2rem 0 0; }
.CTT-goods-list li { margin: 1.2rem 0 0; }
.CTT-goods-list li:nth-of-type(1) { margin-top: 0; }
.CTT-goods-name { line-height: 2.5rem; font-size: 1.7rem; font-weight: bold; text-align: justify; }
.CTT-goods-info { margin: 0.5rem 0 0; }
.CTT-goods-info table { width: 100%; border-spacing: 0; border-style: solid; border-color: #444444; border-width: 0 0 1px 1px; }
.CTT-goods-info table td { padding: 0.7rem 0.5rem; line-height: 2rem; vertical-align: middle; border-style: solid; border-color: #444444; border-width: 1px 1px 0 0; }
.CTT-goods-tr td { width: 50%; }
.CTT-goods-item { line-height: 2rem; }
.CTT-goods-item em { white-space: nowrap; }
.CTT-goods-total { margin: 1.2rem 0 0; }
.CTT-terms { margin: 1.2rem 0 0; padding: 1.2rem 0 0; }
.CTT-terms-name { line-height: 2.5rem; font-size: 1.7rem; font-weight: bold; text-align: justify; }
.CTT-terms-list li { margin: 0.5rem 0 0; line-height: 2rem; }
.CTT-sealsign { padding: 3rem 0 2rem; }
.CTT-sign b { font-size: 1.5rem; }
.CTT-sign-img { margin-top: 2rem; text-align: center; }
.CTT-sign-img img { width: 12rem; }
.CTT-seal b { font-size: 1.5rem; }
.CTT-seal-img { margin-top: 1rem; }
.CTT-seal-img img { width: 14rem; }
.CTT-sign-btn { margin: 1rem 0 2rem; padding: 0 2rem; height: 4rem; line-height: 4rem; font-size: 1.6rem; }

/* ---- */
.xw-full { position: fixed; top: 0; right: 0; bottom: 0; left: 0; background: rgba(0, 0, 0, 0.9); z-index: 999; }

/* ---- */
.FBR-box { position: absolute; padding: 0 0 4rem; top: 0; right: 0; left: 0; background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0)); z-index: 9999; color: #ffffff; }
.FBR-title { padding: 1rem; font-size: 1.6rem; }
.FBR-close { padding: 1rem; }

/* ---- */
.tabs { padding: 0 1rem; }
.TAB-mbtn { height: 4rem; line-height: 4rem; font-size: 1.6rem; }
</style>
<style>
/* ---- */
.album-box { width: 100%; height: 100%; }
</style>